package com.atguigu.ssyx.acl.service.impl;
import java.util.ArrayList;
import java.util.Date;

import com.atguigu.ssyx.acl.mapper.AdminRoleMapper;
import com.atguigu.ssyx.acl.service.AdminRoleService;
import com.atguigu.ssyx.model.acl.AdminRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 杨林
 * @create 2023-07-10 17:49 星期一
 * description:
 */
@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole> implements AdminRoleService {

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 给用户分配角色
     * @param adminId
     * @param roleIds
     */
    @Override
    @Transactional
    public void assignsRoles(Long adminId, List<Long> roleIds) {
        //第一步：先删除当前用户已有的角色
        //方案1：在xml中写sql语句
        //adminRoleMapper.deleteByAdminId(adminId);
        //方案2：通过MybatisPlus实现，较为简单
        LambdaQueryWrapper<AdminRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminRole::getAdminId,adminId);
        adminRoleMapper.delete(wrapper);

        //第二步：给当前用户添加新角色
        //构建需要添加的对象
        List<AdminRole> adminRoles = new ArrayList<>();
        for (Long roleId : roleIds) {
            AdminRole adminRole = new AdminRole();
            adminRole.setRoleId(roleId);
            adminRole.setAdminId(adminId);
            //id自增
//            adminRole.setId(0L);
            adminRole.setCreateTime(new Date());
            adminRole.setUpdateTime(new Date());
            adminRole.setIsDeleted(0);
            //错误写法如下：（会造成巨大的数据库压力）
            //adminRoleMapper.insert(adminRole);
            adminRoles.add(adminRole);
        }
        //批量添加操作  (在IService中提供了批量插入的方法)
        adminRoleMapper.batchInset(adminRoles);
    }
}
